package com.jsj.isdt.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

public class DruidUtils {
    private static DataSource ds; // 数据源
    static {  //读取JDBC配置文件
        // 1.创建Properties集合类
        Properties pro = new Properties();
        try {
            // 2.通过反射机制读取配置文件
            pro.load(DruidUtils.class.getClassLoader().getResourceAsStream("db.properties"));
            // 3.获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * 获取连接池
     */
    public static DataSource getDataSource() throws SQLException {
        return ds;
    }

    /*
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /*
     * 关闭连接
     */
    public static void close(ResultSet rs, PreparedStatement pst, Connection con) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
//    关闭连接
    public static void close(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}